const TMG_log_db_name = "TransformMaterialGoods";

function can_purchase(argument) {
	return this.getPerm().can_purchase;
};
var skill = {
	_addPurchase: function(bus_purchase_id) {
		var purchase_id_list = this.getPurchaseIdList();
		purchase_id_list.unshift(bus_purchase_id);
		this.save();
	},
	_removePurchase: function(bus_purchase_id) {
		$Array.remove(this.getPurchaseIdList(), bus_purchase_id);
		this.save();
	},
	addPurchase: function(bus_purchase_info) {
		bus_purchase_info.bus_id = this._id;
		return new BusPurchaseCon(bus_purchase_info);
	},
	updatePurchase: function(bus_purchase_id, bus_purchase_info) {
		var purchase = this.getPurchaseById(bus_purchase_id);
		purchase.setInfo(bus_purchase_info);
		return purchase;
	},
	removePurchase: function(bus_purchase_id) {
		var purchase = this.getPurchaseById(bus_purchase_id);
		purchase.destroy();
	},
	// 源材料操作
	_addMaterial: function(bus_material_id) {
		var material_id_list = this.getMaterialIdList();
		material_id_list.unshift(bus_material_id);
		this.save();
	},
	_removeMaterial: function(bus_material_id) {
		$Array.remove(this.getMaterialIdList(), bus_material_id);
		this.save();
	},
	addMaterial: function(bus_material_info) {
		bus_material_info.bus_id = this._id;
		return new BusMaterialCon(bus_material_info);
	},
	updateMaterial: function(bus_material_id, bus_material_info) {
		var material = this.getMaterialById(bus_material_id);
		material.setInfo(bus_material_info);
		return material;
	},
	removeMaterial: function(bus_material_id) {
		var material = this.getMaterialById(bus_material_id);
		material.destroy();
	},
	// 原材料转换成商品
	transformMaterialsToGoods: function(goods_list_info, material_list_info) {
		var log_id = "TMG" + (new Date).format("yyyyMMdd") + Math.random().toFixed(8).substr(2);
		var log_info = {
			_id: log_id,
			material_list_info: [],
			goods_list_info: []
		};
		/* 数据校验 */
		log_info.material_list_info = material_list_info.map((material_info, index) => {
			var material = this.getMaterialById(material_info.id);
			if (material_info.num > material.num) {
				throwCusError(`第${index}项材料：“${material.品名}”的库存量为${material.num}，不足${material_info.num}`)
			}
			material_info.material = material;
			return {
				material_id: material._id,
				before_num: material.num,
				use_num: parseFloat(material_info.num)
			}
		});
		log_info.goods_list_info = goods_list_info.map((goods_info) => {
			var goods = this._getGoods(goods_info.id);
			goods_info.goods = goods;
			if (goods_info.num <= 0) {
				throwCusError(`第${index}项商品：转换数量有误：${goods_info.num}`)
			}
			return {
				goods_id: goods._id,
				before_num: goods.num,
				add_num: parseInt(goods_info.num)
			}
		});
		/* 执行材料商品转换 */
		material_list_info.forEach((material_info) => {
			material_info.material._useNum(material_info.num, `材料商品转换，转换日志ID：${log_id}`)
		});
		goods_list_info.forEach((goods_info) => {
			goods_info.goods._addNum(goods_info.num)
		});
		db.insert(TMG_log_db_name, log_info);
		return log_info;
	},
	getTMGLogs: function(num, page, options) {
		var log_list = db.find_all(TMG_log_db_name);
		var res = [];
		var num = ~~num || 20;
		var page = ~~page;
		var start_index = Math.min(num * page, log_list.length);
		var end_inex = Math.min(start_index + page, log_list.length) - 1;
		// 倒序取出
		for (var i = end_inex; res.length < num; i -= 1) {
			log_list[i] && res.push(log_list[i]);
		}
		return res;
	}
};
//权限限制注入
Object.keys(skill).forEach(function(method_name) {
	skill[method_name] = skill[method_name].perm(can_purchase, "权限不足， 需要与管理员联系才能使用采购功能")
});
skill.canMA = can_purchase;
skill = Object.assign(skill, {
	/*
	 * 不受权限限制的
	 */
	getPurchaseIdList: function() {
		return this.purchases || (this.purchases = []);
	},
	getPurchaseList_WithPageInfo: function(num, page, options) {
		num = ~~num || 20;
		page = ~~page;
		options || (options = {});
		var all_purchase_id_list = this.getPurchaseIdList();
		if (!(options.filter && options.filter.hasOwnProperty("state"))) {
			var purchase_id_list = data_cut.page(all_purchase_id_list, num, page);
			console.log(purchase_id_list);
			var purchase_list = purchase_id_list.map(purchase_id => {
				var purchase = this.getPurchaseById(purchase_id, "stop_error");
				if (!purchase) {
					all_purchase_id_list = $Array.remove(all_purchase_id_list, purchase_id);
				}
				return purchase;
			}).filter(purchase => purchase);

			// 如果长度不一样，那么就有无效id被remove掉，立刻保存
			if (purchase_list.length !== purchase_id_list.length) {
				this.purchases = all_purchase_id_list;
				this.save();
			}
			var total_num = all_purchase_id_list.length;
		} else {
			// 手动索引过滤模式
			var start_index = num * page;
			var all_purchase_list = [];
			all_purchase_id_list.forEach(purchase_id => {
				var purchase = this.getPurchaseById(purchase_id, "stop_error");
				purchase && all_purchase_list.push(purchase);
			});
			if (all_purchase_id_list.length !== all_purchase_list.length) {
				this.purchases = all_purchase_list.map(purchase => purchase._id);
				this.save();
			}


			var filter_state = parseInt(options.filter && options.filter.state) || 0;

			var state_purchase_list = all_purchase_list.filter(purchase => purchase.state === filter_state);

			var purchase_list = data_cut.page(state_purchase_list, num, page);

			var total_num = state_purchase_list.length;
		}

		return {
			total_num: total_num,
			total_page: Math.round(total_num / num) || 1, //至少一页
			list: purchase_list.map(item => {
				item = Object.assign({}, item);
				delete item.material_list;
				return item;
			}),
			page: ~~page,
			num: num
		}
	},
	getPurchaseById: function(bus_purchase_id, is_stop_error) {
		var purchase = BusPurchaseCon.get(bus_purchase_id);
		if (!purchase) {
			is_stop_error || throwCusError("找不到指定采购单");
			return
		}
		if (purchase.bus_id !== this._id) {
			is_stop_error || throwCusError("指定采购单不属于指定商家")
			return
		}
		return purchase
	},
	// 材料的操作
	buildMaterial: function(info) {
		var material;
		this.getMaterialIdList()
			.some(material_id => {
				var material_item = this.getMaterialById(material_id, "stop_error");
				if (material_item.equal(info)) {
					material = material_item;
					return true
				}
			});
		if (!material) {
			material = this.addMaterial(info)
		}
		return material;
	},
	searchMaterialList: function(like_info, len) {
		var res = [];
		len = ~~len || 10;
		this.getMaterialIdList()
			.some(material_id => {
				var material_item = this.getMaterialById(material_id, "stop_error");
				if (material_item.like(like_info)) {
					res.push(material_item)
					return true
				}
				return res.length >= len
			});
		return res;
	},
	getMaterialIdList: function() {
		return this.materials || (this.materials = []);
	},

	getMaterialList_WithPageInfo: function(num, page, options) {
		num = ~~num || 20;
		page = ~~page;
		options || (options = {});
		var all_material_id_list = this.getMaterialIdList();
		var material_id_list = data_cut.page(all_material_id_list, num, page);
		var material_list = material_id_list.map(material_id => {
			var material = this.getMaterialById(material_id, "stop_error");
			if (!material) {
				all_material_id_list = $Array.remove(all_material_id_list, material_id);
			}
			return material;
		}).filter(material => material);

		// 如果长度不一样，那么就有无效id被remove掉，立刻保存
		if (material_list.length !== material_id_list.length) {
			this.materials = all_material_id_list;
			this.save();
		}
		var total_num = all_material_id_list.length;


		return {
			total_num: total_num,
			total_page: Math.round(total_num / num) || 1, //至少一页
			list: material_list.map(item => {
				item = Object.assign({}, item);
				delete item.logs;
				return item;
			}),
			page: ~~page,
			num: num
		}
	},
	getMaterialById: function(material_id, is_stop_error) {
		var material = BusMaterialCon.get(material_id);
		if (!material) {
			is_stop_error || throwCusError("找不到指定原材料");
			return
		}
		if (material.bus_id !== this._id) {
			is_stop_error || throwCusError("指定原材料不属于指定商家")
			return
		}
		return material
	},
});

module.exports = skill;

var db = require("../db/index");
var DomainCon = require("../domain/_con");
var GoodsCon = require("../goods/_con");
var UserCon = require("../../core/user/_con");
var BusCon = require("../../core/bus/_con");
var BusMACon = require("../bus.MA/_con");
var BusPurchaseCon = require("../bus.purchase/_con");
var BusMaterialCon = require("../bus.material/_con");
var LeagueCon = require("../league/_con");
var BuffCon = require("../buff/_con");
var BusUserBindCon = require("../bus_user_bind/_con");
var BusGuideCon = require("../bus.guide/_con");
var CommentCon = require("../comment/_con");
var config = require("../_include/config");
var data_cut = require("../_include/data_cut");
var helper = require("../_include/helper");
var md5 = require("../_include/md5");
var $Object = require("../_include/$.Object");
var $Array = require("../_include/$.Array");
var tld = require('tldjs');
var fs = require("fs");
var Fiber = require('fibers');